<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>小球碰撞</title>
</head>
<style>
    canvas{
        box-shadow: 0 0 10px #333;
    }
</style>
<body onload="init()">
    <canvas id="canvas" height="300" width="400">
        浏览器不支持canvas
    </canvas>
</body>
</html>

<script>
    var canvas = document.getElementById("canvas");
    function init(){
        if(!canvas.getContext){
            return
        }
        var ctxt = canvas.getContext('2d');
        function Ball(x,y,r,speedX,speedY,color){//小球对象
            this.x = x;
            this.y = y;
            this.r = r;
            this.speedX = speedX;
            this.speedY = speedY;
            this.color = color
        }

        Ball.prototype.ball = function(){//初始化小球
            ctxt.beginPath();
            ctxt.fillStyle = this.color;
            ctxt.arc(this.x,this.y,this.r,0,Math.PI*2);
            ctxt.fill()
        };
        Ball.prototype.move = function(){
            this.x += this.speedX;
            this.y += this.speedY;
            if(this.x>canvas.width-this.r){
                this.speedX *= -1
            }else if(this.x<this.r){
                this.speedX *= -1
            }
            if(this.y>canvas.height-this.r){
                this.speedY *= -1
            }else if(this.y<this.r){
                this.speedY *=  -1
            }
        };
        var ball1 = new Ball(20,30,20,2,6,'red');
        var ball2 = new Ball(280,80,20,8,6,'green');
        var ball3 = new Ball(100,100,20,2,3,'pink');
        // ball1.ball();
        // ball1.move();
        // ball2.ball();
        // ball2.move();
        function animate(){
            ctxt.clearRect(0,0,canvas.width,canvas.height);
            ball1.ball();
            ball1.move();
            ball2.ball();
            ball2.move();

            if(ballHit(ball1,ball2)){
                console.log('11');
                ball1.speedX *= -1;
                ball1.speedY *= -1;
                ball2.speedX *= -1;
                ball2.speedY *= -1;
            }
            window.requestAnimationFrame(animate)
        }
        animate();

        function ballHit(ball1,ball2){//小球之间的碰撞
            var minX1 = ball1.x-ball1.r;
            var minX2 = ball2.x-ball2.r;
            var minY1 = ball1.y-ball1.r;
            var minY2 = ball2.y-ball2.r;

            var maxX1 = ball1.x + ball1.r;
            var maxX2 = ball2.x + ball2.r;
            var maxY1 = ball1.y + ball1.r;
            var maxY2 = ball2.y + ball2.r;

            var minX = Math.max(minX1,minX2);
            var minY = Math.max(minY1,minY2);
            var maxX = Math.min(maxX1,maxX2);
            var maxY = Math.min(maxY1,maxY2);

            if(minX<maxX && minY < maxY){
                //左边的小球的右侧小于右边小球的左侧 上侧小于下侧   就发生碰撞
                console.log('000');
                return true
            }else{
                return false
            }
        }
    }
</script>
